import React from 'react';
import { Button, Card, Col, DatePicker, Form, Input, Row, Select, Spin, TimePicker, Table, Icon, Empty, Tabs, Pagination } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import moment from 'moment';
import ApiCounts from '@/pages/DataStatistics/APIStatistics/apiCounts';
import { getApiCount, getApiRecord, exportApiCount, exportApiRecord, doChatRecords } from '@/services/datastatistics';
import { fetchApiListById } from '@/services/basiccapacity'
import ContextModal from '@/utils/contextModal';
import { formatMessage } from 'umi-plugin-react/locale';
import apiStyles from './apiStyles.css'
const { TabPane } = Tabs;

class APIStatistics extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      activeKey: '1',
      queryData: {
        beginDate: moment().subtract('7', 'days').format('YYYY-MM-DD'),
        endDate: moment().format('YYYY-MM-DD'),
        // beginHour: '00',
        // endHour: '24',
      },
      apiCountList: [],
      endHourOptions: [
        {
          value: '01',
          disabled: false
        },
        {
          value: '02',
          disabled: false
        },
        {
          value: '03',
          disabled: false
        },
        {
          value: '04',
          disabled: false
        },
        {
          value: '05',
          disabled: false
        },
        {
          value: '06',
          disabled: false
        },
        {
          value: '07',
          disabled: false
        },
        {
          value: '08',
          disabled: false
        },
        {
          value: '09',
          disabled: false
        },
        {
          value: '10',
          disabled: false
        },
        {
          value: '11',
          disabled: false
        },
        {
          value: '12',
          disabled: false
        },
        {
          value: '13',
          disabled: false
        },
        {
          value: '14',
          disabled: false
        },
        {
          value: '15',
          disabled: false
        },
        {
          value: '16',
          disabled: false
        },
        {
          value: '17',
          disabled: false
        },
        {
          value: '18',
          disabled: false
        },
        {
          value: '19',
          disabled: false
        },
        {
          value: '20',
          disabled: false
        },
        {
          value: '21',
          disabled: false
        },
        {
          value: '22',
          disabled: false
        },
        {
          value: '23',
          disabled: false
        },
        {
          value: '24',
          disabled: false
        },
      ],
      apiTotalCount: 0,
      apiList: [],
      tableQuery: {
        apiId: '',
        search: '',
        current: 1,
        size: 10,
        status: -1
      },
      tableLoading: true,
      tableList: [],
      tableTotal: 0,
      contextModalVisible: false,
      contextMessage: []
    };
  }

  componentDidMount() {
    this.getData();
  }

  /**
   * tab切换回调
   */
  tabCallback = key => {
    this.setState({ activeKey: key }, () => {
      switch (key) {
        case '1':
          this.getData();
          break;
        case '2':
          this.getAllApi();
          this.getTableData();
          break;
      }
    })
  }

  /**
   * 获取条形图数据
   */
  getData = async () => {
    const { queryData } = this.state;
    const res = await getApiCount(queryData);
    let records = res.record;
    if (!res.record || res.record.length === 0) {
      records = [{ x: formatMessage({ id: 'apiStatistics.noData' }), y: 0 }]
    };
    this.setState({ apiCountList: records, apiTotalCount: res.count });
  };

  /**
   * 获取全部接口查询条件数据
   */
  getAllApi = async () => {
    const res = await fetchApiListById({ current: 1, size: 999999 });
    this.setState({ apiList: res.records })
  }

  /**
   * 获取表格数据
   */
  getTableData = () => {
    this.setState({ tableLoading: true }, async () => {
      const { queryData, tableQuery } = this.state;
      const obj = { ...queryData, ...tableQuery };
      const res = await getApiRecord(obj);
      this.setState({
        tableLoading: false,
        tableTotal: res.total,
        tableList: res.records
      })
    })
  }

  /**
   * 根据条件查询
   * @returns {*}
   */
  queryByCondition = () => {
    let { queryData, tableQuery } = this.state;
    const info = this.props.form.getFieldsValue();
    queryData.beginDate = info.time[0].format('YYYY-MM-DD');
    queryData.endDate = info.time[1].format('YYYY-MM-DD');
    // queryData.beginHour = info.beginHour.format('HH');
    // queryData.endHour = info.endHour;
    tableQuery.current = 1;
    this.setState({ queryData, tableQuery }, () => {
      this.getData();
      this.getTableData();
    });
  };

  /**
   * 根据表格查询条件
   */
  queryByTableCondition = () => {
    let { queryData, tableQuery } = this.state;
    const info = this.props.form.getFieldsValue();
    queryData.beginDate = info.time[0].format('YYYY-MM-DD');
    queryData.endDate = info.time[1].format('YYYY-MM-DD');
    // queryData.beginHour = info.beginHour.format('HH');
    // queryData.endHour = info.endHour;
    tableQuery.current = 1;
    tableQuery.size = 10;
    tableQuery.search = info.search;
    tableQuery.apiId = info.apiId;
    tableQuery.status = info.status
    this.setState({ tableQuery }, () => {
      this.getTableData()
    })
  }

  /**
   *
   * @param {分页查询} value
   */
  queryByChange = (current, size) => {
    let { tableQuery } = this.state;
    tableQuery.current = current;
    tableQuery.size = size;
    this.setState({ tableQuery }, () => {
      this.getTableData();
    })
  }

  /**
   * 修改起始小时 重置结束小时
   * @returns {number[]}
   */
  changeResetHour = (value) => {
    this.props.form.resetFields(['endHour'])
    const start = value.format('HH');
    let { endHourOptions } = this.state;
    for (let item of endHourOptions) {
      if (parseInt(item.value) < parseInt(start)) {
        item.disabled = true;
      } else {
        item.disabled = false;
      }
    };
    this.setState({ endHourOptions })
  };

  /**
   *
   * @returns 条形图数据导出
   */
  exportCount = async () => {
    const { queryData } = this.state;
    const res = await exportApiCount(queryData);
  }

  /**
   *
   * @returns 导出表格数据
   */
  exportRecord = async () => {
    const { queryData, tableQuery } = this.state;
    const obj = { ...queryData, ...tableQuery };
    const res = await exportApiRecord(obj);
  }

  /**
   * 获取上下文
   * @returns {*}
   */
  getChatRecords = async (row) => {
    const obj = {
      sessionId: row.sessionId,
      time: moment(row.createTime).format('YYYY-MM-DD HH:mm:ss'),
      robotId: row.robotId
    };
    const res = await doChatRecords(obj);
    this.setState({
      contextMessage: res,
      contextModalVisible: true
    })
  }

  /**
   * 关闭上下文
   * @returns {*}
   */
  cancelContextModal = () => {
    this.setState({
      contextModalVisible: false,
      contextMessage: []
    })
  }

  render() {
    const {
      activeKey, loading, apiCountList, list, endHourOptions, apiTotalCount, apiList,
      tableList, tableLoading, tableQuery, tableTotal, contextModalVisible, contextMessage,
    } = this.state;
    const { getFieldDecorator } = this.props.form;
    const columns = [
      {
        title: formatMessage({ id: 'apiStatistics.apiInterface' }),
        dataIndex: 'apiName',
        width: 180
      },
      {
        title: formatMessage({ id: 'apiStatistics.user' }),
        dataIndex: 'userId',
        width: 150
      },
      {
        title: formatMessage({ id: 'apiStatistics.time' }),
        dataIndex: 'createTime',
        width: 150
      },
      {
        title: formatMessage({ id: 'apiStatistics.callResult' }),
        dataIndex: 'result',
        width: 100
      },
      {
        title: formatMessage({ id: 'apiStatistics.callReturn' }),
        dataIndex: 'info',
        width: 100,
        render: (text) => {
          return <div className={apiStyles.txt_cut} title={text}>{text}</div>
        }
      },
      {
        title: formatMessage({ id: 'apiStatistics.operation' }),
        width: 100,
        render: (text, row) => {
          return <span style={{ color: '#3e5bff', cursor: 'pointer' }} onClick={() => this.getChatRecords(row)}>{formatMessage({ id: 'apiStatistics.viewContext' })}</span>
        }
      }
    ];

    return (
      <div style={{ height: '100%' }}>
        <PageHeaderWrapper>
          <Card style={{ height: '100%' }}>
            <Spin spinning={loading}>
              <Tabs activeKey={activeKey} onChange={this.tabCallback}>
                <TabPane tab={<span>{formatMessage({ id: 'apiStatistics.apiCallStatistics' })}{`(${apiTotalCount})`}</span>} key="1">
                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <Form layout={'inline'}>
                      <Form.Item>
                        {getFieldDecorator('time', {
                          initialValue: [moment().subtract('7', 'days'), moment()],
                        })(<DatePicker.RangePicker allowClear={false} style={{ width: '250px' }} />)}
                      </Form.Item>
                      <Form.Item>
                        <Button type={'primary'} onClick={this.queryByCondition}>{formatMessage({ id: 'apiStatistics.query' })}</Button>
                      </Form.Item>
                    </Form>
                    <Button onClick={this.exportCount}>{formatMessage({ id: 'apiStatistics.export' })}</Button>
                  </div>
                  <Row style={{ marginTop: 20 }}>
                    <Col span={24}>
                      <div style={{ height: 'calc(100vh - 274px)', paddingTop: '66px' }}>
                        {apiTotalCount > 0 ? <ApiCounts data={apiCountList} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                      </div>
                    </Col>
                  </Row>
                </TabPane>
                <TabPane tab={<span>{formatMessage({ id: 'apiStatistics.apiCallRecord' })}{`(${tableTotal})`}</span>} key="2">
                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <Form layout={'inline'}>
                      <Form.Item>
                        {getFieldDecorator('time', {
                          initialValue: [moment().subtract('7', 'days'), moment()],
                        })(<DatePicker.RangePicker allowClear={false} style={{ width: '250px' }} />)}
                      </Form.Item>
                      <Form.Item>
                        {getFieldDecorator('status', { initialValue: -1, })(
                          <Select style={{ width: 180 }}>
                            <Select.Option value={-1}>{formatMessage({ id: 'apiStatistics.all' })}</Select.Option>
                            <Select.Option value={1}>{formatMessage({ id: 'apiStatistics.success' })}</Select.Option>
                            <Select.Option value={0}>{formatMessage({ id: 'apiStatistics.failure' })}</Select.Option>
                          </Select>
                        )}
                      </Form.Item>
                      <Form.Item>
                        {getFieldDecorator('apiId', { initialValue: '' })(
                          <Select style={{ width: 180 }}>
                            <Select.Option value={''}>{formatMessage({ id: 'apiStatistics.allInterfaces' })}</Select.Option>
                            {apiList.map(item => {
                              return <Select.Option value={item.id} key={item.id} >{item.name}</Select.Option>
                            })}
                          </Select>
                        )}
                      </Form.Item>
                      <Form.Item>
                        {getFieldDecorator('search')(
                          <Input.Search placeholder={formatMessage({ id: 'apiStatistics.pleaseEnterEmail' })} onSearch={this.queryByTableCondition} />
                        )}
                      </Form.Item>
                      <Form.Item>
                        <Button type={'primary'} onClick={this.queryByTableCondition}>{formatMessage({ id: 'apiStatistics.query' })}</Button>
                      </Form.Item>
                    </Form>
                    <Button onClick={this.exportRecord}>{formatMessage({ id: 'apiStatistics.export' })}</Button>
                  </div>
                  <Row style={{ marginTop: 20 }}>
                    <Table
                      columns={columns}
                      dataSource={tableList}
                      loading={tableLoading}
                      rowKey={(record, index) => index}
                      pagination={false}
                    />
                    {tableTotal > 10 ? (
                      <Pagination
                        style={{ textAlign: 'right', marginTop: 16 }}
                        total={tableTotal}
                        current={tableQuery.current}
                        onChange={this.queryByChange}
                        showQuickJumper={true}
                        showSizeChanger={true}
                        onShowSizeChange={this.queryByChange}
                        pageSizeOptions={['10', '20', '30', '40', '100']}
                      />
                    ) : null}
                  </Row>
                </TabPane>
              </Tabs>
            </Spin>
            <ContextModal visible={contextModalVisible} message={contextMessage} cancelContextModal={this.cancelContextModal} />
          </Card>
        </PageHeaderWrapper>
      </div>
    );
  }
}

export default Form.create()(APIStatistics);
